import { getUserInfo } from '../../utils/storage'
import { roles } from '../../enums/role'
import config from '../../config/index'
import { updateUser } from '../../api/user'
Page({
  data: {
    userInfo: {} as User,
    roles,
    role_label: '',
    config
  },
  initData() {
    const user = getUserInfo()
    if (user) {
      let userInfo = JSON.parse(user)
      userInfo.createdAt = new Date(userInfo.createdAt).toLocaleString()
      this.setData({
        userInfo,
        role_label: this.data.roles.find(item => item.value === JSON.parse(user).role)!.label
      })
    }
  },
  handleChoose(e: any) {
    let that = this
    wx.uploadFile({
      url: config.BaseUrl + '/api/upload/image',
      filePath: e.detail.avatarUrl,
      name: 'file',
      success: (res: any) => {
        if (res.statusCode === config.CREATED_CODE) {
          let imgRes = JSON.parse(res.data)
          let userInfo = that.data.userInfo as unknown as User
          if (userInfo) {
            userInfo.avatar = imgRes.data.path.replace(/\\/g, '/')
            that.setData({
              userInfo: userInfo as any
            })
          }
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      }
    })
  },
  handleInp(e: any) {
    let userInfo = this.data.userInfo
    userInfo.nick_name = e.detail.value
    this.setData({
      userInfo
    })
  },
  async userSub() {
    if (this.data.userInfo) {
      let data = {
        avatar: this.data.userInfo.avatar,
        nick_name: this.data.userInfo.nick_name,
        phone: this.data.userInfo.phone,
      } as User
      const res = await updateUser(this.data.userInfo.id, data)
      if (res.statusCode === config.SUCCESS_CODE) {
        wx.showToast({
          title: res.data,
          icon: 'success'
        })
      }
    }
  },
  onLoad() {
    this.initData()
  },
})